#include <GL/gl.h>

#include "foreach.hpp"
#include "line_chart_widget.hpp"

namespace gui {

line_chart_widget::line_chart_widget() : longest_plot_(0), highest_point_(0)
{}

void line_chart_widget::add_plot(const std::vector<int>& data)
{
	data_.push_back(data);
	if(data.size() > longest_plot_) {
		longest_plot_ = data.size();
	}

	foreach(int d, data) {
		if(d > highest_point_) {
			highest_point_ = d;
		}
	}
}

void line_chart_widget::handle_draw() const
{
	assert(highest_point_ > 0);
	assert(longest_plot_ > 0);
	glDisable(GL_TEXTURE_2D);
	glLineWidth(1);
	glBegin(GL_LINES);
	glColor4f(1.0, 1.0, 1.0, 1.0);
	//draw the border
	glVertex3f(x(), y(), 0);
	glVertex3f(x() + width(), y(), 0);
	glVertex3f(x() + width(), y(), 0);
	glVertex3f(x() + width(), y() + height(), 0);
	glVertex3f(x() + width(), y() + height(), 0);
	glVertex3f(x(), y() + height(), 0);
	glVertex3f(x(), y() + height(), 0);
	glVertex3f(x(), y(), 0);

	for(int n = 0; n != longest_plot_; ++n) {
		const int xpos = x() + (width()*n)/longest_plot_;
		glVertex3f(xpos, y() + height(), 0);
		glVertex3f(xpos, y() + height() - 5, 0);
	}

	glEnd();

	foreach(const std::vector<int>& plot, data_) {
		glBegin(GL_LINE_STRIP);
		for(int n = 0; n != plot.size(); ++n) {
			const int xpos = x() + (width()*n)/longest_plot_;
			const int ypos = y() + height() - (height()*plot[n])/highest_point_;
			glVertex3f(xpos, ypos, 0);
		}
		glEnd();
	}
	
	glEnable(GL_TEXTURE_2D);
}
}
